﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestionPedago.EntityContext;
using System.Reflection;
using System.IO;

namespace ESGenerator {
    class Program {
        static void Main(string[] args) {
            foreach(Type type in GetAllClasses("GestionPedago.EntityContext")) {
                if(type.Name.Contains("Entities") || type.Name.Contains("EntityConnection")) {
                    continue;
                }
                string genere = ClassGenerator.PerformClass(type, "GestionPedago.Services.Commun.ES");
                string mappeur = MapperGenerator.PerformClass(type, "GestionPedago.Services.Commun.Mapping");

                EcritureFichier(type.Name + "ES.cs", genere);
                EcritureFichier("Mappers/" + type.Name + "Mappeur.cs", mappeur);
            }

            Console.ReadKey();
        }

        private static void EcritureFichier(string fileName, string contenu) {
            string nomFichier = fileName;

            try {

                // Instanciation du StreamWriter avec passage du nom du fichier 
                StreamWriter monStreamWriter = new StreamWriter("../../Genere/" + nomFichier);

                // Caractère de nouvelle ligne
                monStreamWriter.NewLine = "\n";

                //Ecriture du texte dans votre fichier 
                monStreamWriter.WriteLine(contenu);

                // Fermeture du StreamWriter (Très important) 
                monStreamWriter.Close();
            } catch(Exception ex) {
                // Code exécuté en cas d'exception 
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Fichier " + nomFichier + " créé");
        }

        /// <summary>
        /// Method to populate a list with all the class
        /// in the namespace provided by the user
        /// </summary>
        /// <param name="nameSpace">The namespace the user wants searched</param>
        /// <returns></returns>
        public static List<Type> GetAllClasses(string nameSpace) {
            //create an Assembly and use its GetExecutingAssembly Method
            Assembly asm = Assembly.GetAssembly(typeof(Entities));

            //create a list for the namespaces
            List<Type> namespaceList = new List<Type>();

            //loop through all the "Types" in the Assembly using
            //the GetType method:
            foreach(Type type in asm.GetTypes()) {
                if(type.Namespace == nameSpace)
                    namespaceList.Add(type);
            }

            //return the list
            return namespaceList;
        }
    }

}
